//
//  HMHomeController.swift
//  HMSlender
//
//  Created by 赵少朋赵少朋 on 17/1/16.
//  Copyright © 2017年 ITheima. All rights reserved.
//

import UIKit

let homeCellId = "homeCellID"

class HMHomeController: HMBasicController {
    
    
    
    lazy var homeViewModel: HMHomeViewModel = HMHomeViewModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        if isLogin {
            
            // 插入下拉提示label
            navigationController?.view.insertSubview(pullDownLabel, belowSubview: (navigationController?.navigationBar)!)
            setLoginNavUI()
            loadData()
            
            tabView.dataSource = self
            tabView.delegate = self
            
            tabView.register(HMHomeCell.self, forCellReuseIdentifier: homeCellId)
            //设置预估行高
            tabView.estimatedRowHeight = 200
            //自动计算行高
            tabView.rowHeight = UITableViewAutomaticDimension
            //下拉刷新视图
            tabView.addSubview(refreshView)
            //监听下拉事件
            refreshView.addTarget(self, action: #selector(refreshAction), for: UIControlEvents.valueChanged)
            /// 底部风火轮view
            tabView.tableFooterView = indicatorView
            
        }
        
        
    }
    
    
    // MARK: 登陆状态导航栏控件
    func setLoginNavUI () {
        navigationItem.rightBarButtonItem = UIBarButtonItem(imgName: "navigationbar_pop", target: self, action: #selector(rightItemClick))
    
        navigationItem.leftBarButtonItem = UIBarButtonItem(imgName: "navigationbar_friendsearch", title: nil, target: self, action: #selector(leftItemClick))
        
   
    }
    
    //MARK: 左边item点击事件
    func leftItemClick() {
        
        print("左边item点击了")
    }
    
    //右边
    func rightItemClick() {
    
        navigationController?.pushViewController(HMPushController(), animated: true)
    }
    //  下拉刷新的风火轮
    fileprivate lazy var indicatorView: UIActivityIndicatorView = {
        let indicatorV = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.whiteLarge)
        indicatorV.color = themeColor
        
        return indicatorV
    }()
    
    fileprivate lazy var refreshView:HMRefreshControl = {
        
        let ref = HMRefreshControl()
        return ref
    }()
    
    fileprivate lazy var pullDownLabel: UILabel = {
    
        let lab = UILabel(textSize: smallTextFont, color: UIColor.white)
        lab.frame = CGRect(x: 0, y: 64 - 35, width: SCREENWIDTH, height: 35)
        lab.textAlignment = .center
        lab.backgroundColor = themeColor
        lab.isHidden = true
        return lab
    }()
   
}



extension HMHomeController {

    //
    
    
}



// MARK: tabView数据源方法
extension HMHomeController: UITableViewDataSource, UITableViewDelegate {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return homeViewModel.dataArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: homeCellId, for: indexPath) as! HMHomeCell
        cell.statusModel = homeViewModel.dataArray[indexPath.row]
        
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        
        if indexPath.row == homeViewModel.dataArray.count - 1 && indicatorView.isAnimating == false {
            
            indicatorView.startAnimating()
            loadData()
        }
    }
    
}



// MARK: 加载主页数据
extension HMHomeController {
    
    func loadData() -> Void {
        
        homeViewModel.loadHomeData(isPullUp: indicatorView.isAnimating) { (isFinish, count) in
            //如果动画没有开启 就表示是在下拉刷新
            if self.indicatorView.isAnimating == false {
            
                self.setupPullDonwTipLabelAnimation(dataCount:count)
            }
            self.endRefreshing()
            
            if isFinish {
                
                self.tabView.reloadData()
                
            }
        }
        
    }
    
    func  endRefreshing() -> Void {
        //停止风火轮动画
        self.indicatorView.stopAnimating()
        // 停止系统刷新控件动画
        self.refreshView.endRefreshing()
    }
    
    func setupPullDonwTipLabelAnimation(dataCount:Int) -> Void {
        
        if pullDownLabel.isHidden == false {
            return
        }
        
        var text:String?
        if dataCount <= 0 {
            
            text = "已经是最新微博了"
        } else {
            text = "更新了\(dataCount)条微博"
        }
        pullDownLabel.text = text
        self.pullDownLabel.isHidden = false
        
        UIView.animate(withDuration: 1.0, animations: {
            
                self.pullDownLabel.transform = CGAffineTransform(translationX: 0, y: 35)
            
        }) { (_) in
            
            UIView.animate(withDuration: 1.0, animations: {
                
                self.pullDownLabel.transform = CGAffineTransform.identity
            }) {(_) in
                //隐藏
                self.pullDownLabel.isHidden = true
                
            }
            
        }
    }
    
    // MARK: 下拉触发事件
    @objc fileprivate func refreshAction() {
        
//        print("下拉刷新")
        self.loadData()
    }
}
    
